<#include "/custom.include">
<#include "/java_copyright.include">
<#assign className = table.className>   
<#assign classNameLower = className?uncap_first>
package ${basepackage}.${namespace}.controller;

import java.io.IOException;
import java.util.List;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import ${basepackage}.ump.entity.UserToken;
import ${basepackage}.${namespace}.entity.${className};
import ${basepackage}.${namespace}.service.I${className}Service;
import ${basepackage}.core.util.*;
import ${basepackage}.core.exception.*;
import ${basepackage}.web.entity.ResultModel;
import ${basepackage}.web.util.ResultUtil;
<#include "/java_imports.include">

/**
 * ${table.tableAlias}的相关请求
 * @author 陶富
 */
@Api(value = "${table.tableAlias}接口", description = "${table.tableAlias}接口")
@RestController
@RequestMapping(value = "/${classNameLower}")
public class ${className}Controller {
	private static final Logger logger = LoggerFactory.getLogger(${className}Controller.class);
	@Autowired
	private I${className}Service ${classNameLower}Service;
	
	/**
     * 查询${table.tableAlias}列表
     *
     * @param ${classNameLower} ${table.tableAlias}实体
     * @return
     *
     */
    @ApiOperation(value = "查询${table.tableAlias}列表", notes = "根据参数查询${table.tableAlias}列表")
    @GetMapping("/list")
    public ResultModel listAll(@RequestBody(required = false) ${className} ${classNameLower},HttpSession session) {
    	String defaultSorter="";
    	<#list table.columns as column><#if (column.columnNameLower == "orderNo")  >
    	defaultSorter = "ORDER_NO asc";		
		</#if><#if (column.columnNameLower == "createDate")  >
    	defaultSorter = "CREATE_DATE desc";		
		</#if></#list>
        return ResultUtil.ok(${classNameLower}Service.findAll(defaultSorter));
    }
    
    /**
     * 查询${table.tableAlias}列表,直接返回json集合
     *
     */
    @ApiOperation(value = "查询${table.tableAlias}列表", notes = "查询${table.tableAlias}列表,直接返回json集合")
    @GetMapping("/jsonList")
    public String jsonListAll(@RequestBody(required = false) ${className} ${classNameLower},HttpSession session) {
    	String defaultSorter="";
    	<#list table.columns as column><#if (column.columnNameLower == "orderNo")  >
    	defaultSorter = "ORDER_NO asc";		
		</#if><#if (column.columnNameLower == "createDate")  >
    	defaultSorter = "CREATE_DATE desc";		
		</#if></#list>
		List<${className}> list = ${classNameLower}Service.findAll(defaultSorter);
        return JSON.Encode(list);
    }
    /**
     * 分页查询${table.tableAlias}列表
     *
     */
    @ApiOperation(value = "分页查询${table.tableAlias}列表", notes = "根据分页及其他查询参数查询${table.tableAlias}列表")
    @GetMapping("/listPage")
    public ResultModel listPage(HttpServletRequest request,HttpSession session) {
    	//分页对象，前台传递的包含查询的参数
		Page page = new Page(request);
		logger.info("前台传递的参数【"+page.toString()+"】");
    	
    	String defaultSorter="";
    	<#list table.columns as column><#if (column.columnNameLower == "orderNo")  >
    	defaultSorter = "ORDER_NO asc";		
		</#if><#if (column.columnNameLower == "createDate")  >
    	defaultSorter = "CREATE_DATE desc";		
		</#if></#list>
		
		if(StringUtil.isEmpty(page.getParam("sortField"))&&StringUtil.isEmpty(page.getSorter())){
			page.addParam("sorter",defaultSorter);
		}
		List<${className}> list = ${classNameLower}Service.findByConditionPage(page);
		page.setData(list);
        return ResultUtil.ok(page);
    }
    /**
	 * 根据分页条件查询${table.tableAlias}集合,提供给grid使用
	 */
    @ApiOperation(value = "查询${table.tableAlias}列表", notes = "根据分页条件查询${table.tableAlias}列表,提供给grid使用")
	@RequestMapping(value = "/gridPage")
	public @ResponseBody String gridPage(HttpServletRequest request){
    	BackResult backResult = null;
    	try {
			//分页对象，前台传递的包含查询的参数
			Page page = new Page(request);
			logger.info("前台传递的参数【"+page.toString()+"】");
			List<${className}> ${classNameLower}List = ${classNameLower}Service.findByConditionPage(page);
			//返回的结果对象，包装了返回值、返回记录数、返回状态
			if(!page.getIsPage()){
				page.setTotal(${classNameLower}List.size());
			}
			backResult = BackResult.successResult(${classNameLower}List, page.getTotal());
		} catch (Exception e) {
			logger.error("查询错误", e);
			backResult = BackResult.failedResult("查询错误，原因："+e.getMessage());
		}
		return JSON.Encode(backResult);
	}
    
    /**
     * 根据主键ID查询${table.tableAlias}
     *
     * @param <#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>
     * @return
     */
    @ApiOperation(value = "查询${table.tableAlias}明细", notes = "根据主键ID查询${table.tableAlias}")
    @ApiImplicitParam(name = "<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>", value = "${table.tableAlias}主键ID", required = true, dataType = "String" , paramType = "path")
    @GetMapping("/query/{<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>}")
    public ResultModel query(@PathVariable(value = "<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>") String <#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>) {
        if(StringUtil.isEmpty(<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>)){
            throw new BusinessException("${table.tableAlias}ID不能为空");
        }
        ${className} ${classNameLower} = ${classNameLower}Service.findById(id);
        return ResultUtil.ok(${classNameLower});
    }
    
    /**
     * 新增${table.tableAlias}
     *
     * @param ${classNameLower} ${table.tableAlias}实体
     * @return
     */
    @ApiOperation(value = "新增${table.tableAlias}", notes = "根据${table.tableAlias}实体新增${table.tableAlias}")
    @PostMapping("/add")
    public ResultModel add(@Valid @RequestBody ${className} ${classNameLower},HttpSession session) {        
    	if(StringUtil.isEmpty(${classNameLower}.get<#list table.pkColumns as column>${column.columnName}<#if column_has_next>,</#if></#list>())){
    		${classNameLower}.set<#list table.pkColumns as column>${column.columnName}<#if column_has_next>,</#if></#list>(GUID.getGuid());
        }
    	<#list table.columns as column><#if (column.isUnique()) && (!column.isPk())  >
		${className} ${classNameLower}By${column.columnName} = null;
		if(${classNameLower}!=null&&${classNameLower}.get${column.columnName}()!=null){
			${classNameLower}By${column.columnName} = ${classNameLower}Service.findBy${column.columnName}(${classNameLower}.get${column.columnName}());
			if(${classNameLower}By${column.columnName}!=null){
				throw new BusinessException("${column.columnAlias}已存在");
			}
		}
		</#if></#list>   
        <#list table.columns as column><#if (column.columnNameLower == "createDate")  >
        UserToken current = SessionUtil.getCurrentUserToken();
        ${classNameLower}.setCreateBy(current!=null&&StringUtil.isNotEmpty(current.getUserName())?current.getUserName():"未知用户");
        ${classNameLower}.setCreateDate(new Date());
		</#if></#list>
        ${classNameLower}Service.add(${classNameLower});
        return ResultUtil.ok(${classNameLower});
    }
    /**
     * 修改${table.tableAlias}
     *
     * @param ${classNameLower} ${table.tableAlias}实体
     * @return
     */
    @ApiOperation(value = "修改${table.tableAlias}", notes = "根据${table.tableAlias}ID修改${table.tableAlias}")
    @PostMapping("/modify")
    public ResultModel modify(@Valid @RequestBody ${className} ${classNameLower},HttpSession session) {
    	if(StringUtil.isEmpty(${classNameLower}.get<#list table.pkColumns as column>${column.columnName}<#if column_has_next>,</#if></#list>())){
    		throw new BusinessException("${table.tableAlias}主键不能为空"); 
        }
    	<#list table.columns as column><#if (column.columnNameLower == "modifyDate")  >
    	UserToken current = SessionUtil.getCurrentUserToken();
        ${classNameLower}.setModifyBy(current!=null&&StringUtil.isNotEmpty(current.getUserName())?current.getUserName():"未知用户");
        ${classNameLower}.setModifyDate(new Date());
		</#if></#list>
		${classNameLower}Service.update(${classNameLower});
        return ResultUtil.ok(${classNameLower});
    }
    /**
     * 根据主键ID删除${table.tableAlias}
     *
     * @param <#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>
     * @return
     */
    @ApiOperation(value = "删除${table.tableAlias}", notes = "根据主键删除${table.tableAlias}")
    @ApiImplicitParam(name = "<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>", value = "${table.tableAlias}主键", required = true, dataType = "String" , paramType = "path")
    @GetMapping("/delete/{<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>}")
    public ResultModel delete(@PathVariable(value = "<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>") String <#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>) {
        if(StringUtil.isEmpty(<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>)){
            throw new BusinessException("${table.tableAlias}主键不能为空");
        }
        ${classNameLower}Service.delete(<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>);
        return ResultUtil.ok();
    }
    /**
     * 根据${table.tableAlias}ID集合批量删除${table.tableAlias}
     *
     * @param <#list table.pkColumns as column>${column.columnNameLower}s<#if column_has_next>,</#if></#list> ${table.tableAlias}ID集合
     * @return ResultModel
     *
     */
    @ApiOperation(value = "批量删除${table.tableAlias}", notes = "根据主键集合批量删除${table.tableAlias}")
    @PostMapping("/delBatchByIds")
    public ResultModel delBatchByIds(@RequestBody List<String> <#list table.pkColumns as column>${column.columnNameLower}s<#if column_has_next>,</#if></#list>) {
        if (<#list table.pkColumns as column>${column.columnNameLower}s<#if column_has_next>,</#if></#list>.size() == 0) {
            throw new BusinessException("${table.tableAlias}主键集合不能为空");
        }
        ${classNameLower}Service.batchDelete(<#list table.compositeIdColumns as c>${c.columnNameFirstLower}<#if c_has_next>,</#if></#list>s);
        return ResultUtil.ok();
   }    
}
